let md5 = require('md5')
let moment = require('moment')
let { request } = require('../databases/db.js')
let svgCaptcha=require('svg-captcha')
let UserList=async (req, res) => {
    let sql = `select * from hg_users`
    let result = await request(sql)
    res.json({
        status: 200,
        data: result
    })
}
let MenuList=async (req, res) => {
    let sql = `SELECT * FROM hg_menus WHERE pid=0`
    let result = await request(sql)
    for (let i = 0; i < result.length; i++) {
        let sql2 = `SELECT * FROM hg_menus WHERE pid=${result[i].id}`
        let result2 = await request(sql2)
        result[i].children = result2
    }
    res.json({
        status: 200,
        data: result
    })
}


let SvgCaptcha = (req,res)=> {
    var captcha = svgCaptcha.create({
        size: 4,//字符的长度
        igonreChars: "o01i",//忽略这些字符
        noise: 1,//干扰线
        color: true,//启用颜色
        background: "#fff",//启用背景颜色
    });
    res.type('svg');
    res.status(200).send(captcha.data)
}


let Login = async (req, res) => {
    let username = req.body.username
    console.log(username);
    let password = md5(req.body.password)
    console.log(password);
    let sql = `select * from hg_users where username="${username}"`
    let result = await request(sql)
    if (result.length > 0) {
        let sql2 = `select * from hg_users where username="${username}" and password="${password}"`
        let result2 = await request(sql2)
        if (result2.length > 0) {
            res.json({
                status: 200,
                msg:"登录成功"
            })
        
        } else {
            res.json({
                status: 1002,
                msg:"用户名或密码错误"
            })
      
        }
    } else {
        res.json({
                status: 1001,
                msg:"用户名不存在"
            })

    } 
}

let Useradd=async (req, res) => {
    // console.log(req.body);

    let { username, phone, age, level, is_show } = req.body
    let is_username_sql = `select *from hg_users where username="${username}"`
    let isUser = await request(is_username_sql)
    if (isUser.length > 0) {
        res.json({
            status: 1002,
            msg: "该用户名已经存在，可以直接登录"
        })
    } else {
        let password = md5(req.body.password)
        let creat_time = moment().format("YYYY-MM-DD hh:mm:ss")
        let add_sql = `INSERT INTO hg_users SET username = "${username}", PASSWORD = "${password}",phone="${phone}", level="${level}",is_show = "${is_show}", create_time = "${creat_time}"`
        let result = await request(add_sql)
        console.log(result);
        if (result.affectedRows == 1) {
            res.json({
                status: 200,
                msg: "添加成功"
            })
        } else {
            res.json({
                status: 1001,
                msg: "添加失败"
            })
        }
    }
}

module.exports={
    UserList,
        MenuList,
        SvgCaptcha,
        Login,
        Useradd
}